package com.linsen.core.ohc.aspect;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.linsen.core.common.aspect.BaseAspect;
import com.linsen.core.common.constant.LinsenConstant;
import com.linsen.core.ohc.annotation.OHCacheable;
import com.linsen.core.ohc.util.OHCacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;

/**
 * @author zhaoyong
 * @date 2023/4/6
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class OHCacheableAspect extends BaseAspect {
    private final OHCacheUtil<Object> ohCacheUtil;

    @Pointcut("@annotation(" + LinsenConstant.LINSEN_APP_PACKAGE + ".core.ohc.annotation.OHCacheable)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        OHCacheable ohCacheable = super.getAnnotation(point, OHCacheable.class);
        String key = ohCacheable.key();
        boolean isCacheNull = ohCacheable.isCacheNull();
        boolean hasKey = this.ohCacheUtil.hasKey(key);
        if (hasKey) {
            Object cache = this.ohCacheUtil.get(key);
            if (ObjUtil.isNull(cache)) {
                if (isCacheNull) {
                    return null;
                }
            } else {
                Method method = this.getMethod(point);
                Class<?> returnType = method.getReturnType();
                return BeanUtil.toBean(cache, returnType);
            }
        }

        Object result = point.proceed();

        if (ohCacheable.seconds() > 0L) {
            this.ohCacheUtil.set(key, result, Duration.ofSeconds(ohCacheable.seconds()));
        } else {
            this.ohCacheUtil.set(key, result);
        }

        return result;
    }
}
